import Vue, { VNode } from 'vue'
import { ComponentModel } from '@TG/interface'
import { isNotEmpty } from '../validate'

/**
 * 构建列表项
 * @param prop 属性（用于绑定 model）
 * @param label 标题
 * @param width 宽
 * @param align 水平对齐
 * @param fixed 固定位置
 * @param template 构建模板
 */
export const buildTableItem = (
  prop: string,
  label?: string,
  width?: string,
  align?: 'left' | 'center' | 'right',
  fixed?: 'left' | 'right',
  template?: ComponentModel
) => {
  const item: ComponentModel = {}
  if (isNotEmpty(template)) {
    Object.assign(item, template)
  }
  const props: Map<string, any> = new Map<string, any>([
    ['prop', prop]
  ])
  if (isNotEmpty(label)) {
    props.set('label', label)
  }
  if (isNotEmpty(width)) {
    props.set('width', width)
  }
  if (isNotEmpty(align)) {
    props.set('align', align)
  }
  if (isNotEmpty(fixed)) {
    props.set('fixed', fixed)
  }
  item.props = Object.assign(props, template?.props)
  return item
}

/**
 * 构建链接格式器
 * @param vm Vue 实例
 * @param configs 链接配置集
 */
export const buildFormatterLink = (vm: Vue, configs: {
  title?: string,
  icon?: string,
  type?: 'primary' | 'success' | 'warning' | 'danger' | 'info',
  click?: Function
}[]) => {
  const links: VNode[] = []
  if (isNotEmpty(configs)) {
    const h = vm.$createElement
    configs.forEach((config, i) => {
      if (i > 0) {
        links.push(h('el-divider', {
          props: { direction: 'vertical' }
        }))
      }
      const title = config.title || ''
      const icon = config.icon || ''
      const type = config.type || 'primary'
      const click = config.click || function() {}
      links.push(h('el-link', {
        props: { icon, type, underline: false }, on: { click }
      }, title))
    })
  }
  return links
}
